﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.MEP.Electric.Common;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;
using HYElectricKernel;
using HYRElectric.Equipment;

namespace HYRElectric.PowerSystem
{
	public partial class DlgPanelSystemDetect : System.Windows.Forms.Form
	{
		public bool Iszero { get; set; }

		public bool CurProj
		{
			get
			{
				return this.m_bProj;
			}
			set
			{
				this.m_bProj = value;
			}
		}

		public ElementId IDView
		{
			get
			{
				if (!this.CurProj)
				{
					return this.doc.ActiveView.Id;
				}
				return ElementId.InvalidElementId;
			}
		}

		public DlgPanelSystemDetect(ExternalCommandData cmdDataIn, EquipExchangeExternalHandler cmdExtrenal, ExternalEvent exEvent)
		{
			this.InitializeComponent();
			this.m_cmdExtrenal = cmdExtrenal;
			this.m_exEvent = exEvent;
			this.cmdData = cmdDataIn;
			UIDocument activeUIDocument = cmdDataIn.Application.ActiveUIDocument;
			this.doc = activeUIDocument.Document;
			this.uiDoc = activeUIDocument;
			this.ShowViewName();
			this.m_dictEleMatchDbFamily = new Dictionary<FamilyInstance, EquipmentExchangeSetInfo>();
			DlgPanelSystemDetect.InitEquipExchangeXML(ref this.m_EquipExchangeXMLSetting);
		}

		public static void InitEquipExchangeXML(ref EquipExchangeXMLSetting xmlSetting)
		{
			string xmlPath = Path.Combine(Product.WorkingLocation, "EquipExchangeSetting.xml");
			YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper();
			xmlHelper.LoadXml(xmlPath, "Project");
			xmlSetting = new EquipExchangeXMLSetting(xmlHelper);
			xmlSetting.Init();
		}

		public void RefreshTab()
		{
			if (this.m_lstElecEquipsInValidInLinkDoc.Count == 0)
			{
				this.tabControl.SelectedIndex = 1;
				return;
			}
			this.tabControl.SelectedIndex = 0;
		}

		private void DlgPanelSystemDetect_Load(object sender, EventArgs e)
		{
			this.m_Hook = new KeyboardHook(base.Handle, WindowHelper.HWndRevit.Handle);
			this.m_Hook.HookStart();
			//base.Icon = Resource.YArchitechIcon;
			this.lvwViewName.Columns[0].Width = this.lvwViewName.Width;
			this.InitData();
			this.checkBoxRotate.Checked = true;
		}

		public void InitData()
		{
			this.splitContainer1.Panel1Collapsed = !this.CurProj;
			if (this.CurProj)
			{
				this.HideExchangeFunction();
			}
			this.UpdateLevelListView();
			this.UpdateEquipListView();
			this.UpdateStatusBar();
			this.RefreshTab();
		}

		private void HideExchangeFunction()
		{
			this.checkBoxRotate.Visible = false;
			this.btnChangeSet.Visible = false;
			this.btnKeywordSet.Visible = false;
			this.btnChangeSign.Visible = false;
			this.treeViewNoDistribut.Size = new Size(this.treeViewNoDistribut.Size.Width, this.treeViewNoDistribut.Size.Height + this.btnChangeSign.Size.Height * 2);
			this.treeViewNoDistribut.CheckBoxes = false;
			this.treeViewNoDistribut.ExpandAll();
		}

		private void UpdateLevelListView()
		{
			this.lvwViewName.Items.Clear();
			this.m_lstSortedLevel = this.GetSortLevels(this.doc, double.MinValue, double.MaxValue);
			this.Iszero = true;
			if (this.m_lstSortedLevel.Count > 0)
			{
				foreach (Element element in this.m_lstSortedLevel)
				{
					if (element is Level)
					{
						this.Iszero = false;
						ListViewItem listViewItem = new ListViewItem();
						listViewItem.Text = element.Name;
						listViewItem.Tag = element.Id;
						this.lvwViewName.Items.Add(listViewItem);
					}
				}
				this.lvwViewName.Items[0].Selected = true;
				this.lvwViewName.Items[0].Focused = true;
			}
		}

		private void UpdateStatusBar()
		{
			int selectedIndex = this.tabControl.SelectedIndex;
			int num = (selectedIndex == 0) ? (this.m_lstElecEquipsInValid.Count + this.m_lstElecEquipsInValidInLinkDoc.Count) : (this.m_lstElecEquipsValid.Count + this.m_lstElecEquipsValidInLinkDoc.Count);
			string str = (selectedIndex == 0) ? "未配电" : "已配电";
			this.toolStripStatusLabel.Text = "总项目设备：";
			ToolStripStatusLabel toolStripStatusLabel = this.toolStripStatusLabel;
			toolStripStatusLabel.Text += num.ToString();
			ToolStripStatusLabel toolStripStatusLabel2 = this.toolStripStatusLabel;
			toolStripStatusLabel2.Text += "个";
			ToolStripStatusLabel toolStripStatusLabel3 = this.toolStripStatusLabel;
			toolStripStatusLabel3.Text += str;
		}

		private void UpdateEquipListView()
		{
			if (!this.CurProj)
			{
				this.InitElecEquipData();
				this.treeViewNoDistribut.Nodes.Clear();
				TreeNode treeNode = new TreeNode("当前模型");
				this.treeViewNoDistribut.Nodes.Add(treeNode);
				List<FamilyInstance> lstEquipsLevelAll = this.m_lstElecEquipsInValid.Cast<FamilyInstance>().ToList<FamilyInstance>();
				Utility.UpdateEquipInTreeView(treeNode, lstEquipsLevelAll);
				TreeNode treeNode2 = new TreeNode("链接模型");
				this.treeViewNoDistribut.Nodes.Add(treeNode2);
            //    IEnumerator<string> enumerator = (from e in this.m_lstLinkDoc;
            //    select e.PathName).GetEnumerator())
            //    {
            //        while (enumerator.MoveNext())
            //        {
            //            string strLinkDocName = enumerator.Current;
            //            TreeNode treeNode3 = new TreeNode(strLinkDocName);
            //            treeNode2.Nodes.Add(treeNode3);
            //            List<FamilyInstance> lstEquipsLevelAll2 = (from e in this.m_lstElecEquipsInValidInLinkDoc
            //            where e.Document.PathName == strLinkDocName
            //            select e).ToList<Element>().Cast<FamilyInstance>().ToList<FamilyInstance>();
            //            Utility.UpdateEquipInTreeView(treeNode3, lstEquipsLevelAll2);
            //        }
            //    }
            //    this.treeViewNoDistribut.SetCheckStatus(this.treeViewNoDistribut.Nodes[1], true);
            //    this.InitSelInfo(this.treeViewNoDistribut.Nodes[1]);
            //    this.treeViewNoDistribut.ExpandAll();
            //    this.treeViewDistribut.Nodes.Clear();
            //    TreeNode treeNode4 = new TreeNode("当前模型");
            //    this.treeViewDistribut.Nodes.Add(treeNode4);
            //    List<FamilyInstance> lstEquipsLevelAll3 = this.m_lstElecEquipsValid.Cast<FamilyInstance>().ToList<FamilyInstance>();
            //    Utility.UpdateEquipInTreeView(treeNode4, lstEquipsLevelAll3);
            //    TreeNode treeNode5 = new TreeNode("链接模型");
            //    this.treeViewDistribut.Nodes.Add(treeNode5);
            //    IEnumerator<string> enumerator = (from e in this.m_lstLinkDoc;
            //    select e.PathName).GetEnumerator())
            //    {
            //        while (enumerator.MoveNext())
            //        {
            //            string strLinkDocValidName = enumerator.Current;
            //            TreeNode treeNode6 = new TreeNode(strLinkDocValidName);
            //            treeNode5.Nodes.Add(treeNode6);
            //            List<FamilyInstance> lstEquipsLevelAll4 = (from e in this.m_lstElecEquipsValidInLinkDoc
            //            where e.Document.PathName == strLinkDocValidName
            //            select e).ToList<Element>().Cast<FamilyInstance>().ToList<FamilyInstance>();
            //            Utility.UpdateEquipInTreeView(treeNode6, lstEquipsLevelAll4);
            //        }
            //    }
            //    this.treeViewDistribut.ExpandAll();
            //    return;
            //}
            //ElementId elementId = this.lvwViewName.SelectedItems[0].Tag as ElementId;
            //Level level = this.doc.GetElement(elementId) as Level;
            //if (level == null)
            //{
            //    return;
            //}
            //this.InitElecEquipData();
            //this.treeViewNoDistribut.Nodes.Clear();
            //TreeNode treeNode7 = new TreeNode("当前模型");
            //this.treeViewNoDistribut.Nodes.Add(treeNode7);
            //List<FamilyInstance> levelValidEquips = this.GetLevelValidEquips(this.m_lstElecEquipsInValid, level);
            //Utility.UpdateEquipInTreeView(treeNode7, levelValidEquips);
            //TreeNode treeNode8 = new TreeNode("链接模型");
            //this.treeViewNoDistribut.Nodes.Add(treeNode8);
            //IEnumerator<string> enumerator = (from e in this.m_lstLinkDoc;
            //select e.PathName).GetEnumerator())
            //{
            //    while (enumerator.MoveNext())
            //    {
            //        string strLinkDocName = enumerator.Current;
            //        TreeNode treeNode9 = new TreeNode(strLinkDocName);
            //        treeNode8.Nodes.Add(treeNode9);
            //        List<Element> lstEquips = (from e in this.m_lstElecEquipsInValidInLinkDoc
            //        where e.Document.PathName == strLinkDocName
            //        select e).ToList<Element>();
            //        List<FamilyInstance> levelValidEquips2 = this.GetLevelValidEquips(lstEquips, level);
            //        Utility.UpdateEquipInTreeView(treeNode9, levelValidEquips2);
            //    }
            //}
            //this.treeViewNoDistribut.SetCheckStatus(this.treeViewNoDistribut.Nodes[1], true);
            //this.InitSelInfo(this.treeViewNoDistribut.Nodes[1]);
            //this.treeViewNoDistribut.ExpandAll();
            //this.treeViewDistribut.Nodes.Clear();
            //TreeNode treeNode10 = new TreeNode("当前模型");
            //this.treeViewDistribut.Nodes.Add(treeNode10);
            //List<FamilyInstance> levelValidEquips3 = this.GetLevelValidEquips(this.m_lstElecEquipsValid, level);
            //Utility.UpdateEquipInTreeView(treeNode10, levelValidEquips3);
            //TreeNode treeNode11 = new TreeNode("链接模型");
            //this.treeViewDistribut.Nodes.Add(treeNode11);
            //IEnumerator<string> enumerator = (from e in this.m_lstLinkDoc;
            //select e.PathName).GetEnumerator())
            //{
            //    while (enumerator.MoveNext())
            //    {
            //        string strLinkDocValidName = enumerator.Current;
            //        TreeNode treeNode12 = new TreeNode(strLinkDocValidName);
            //        treeNode11.Nodes.Add(treeNode12);
            //        List<Element> lstEquips2 = (from e in this.m_lstElecEquipsValidInLinkDoc
            //        where e.Document.PathName == strLinkDocValidName
            //        select e).ToList<Element>();
            //        List<FamilyInstance> levelValidEquips4 = this.GetLevelValidEquips(lstEquips2, level);
            //        Utility.UpdateEquipInTreeView(treeNode12, levelValidEquips4);
            //    }
            }
			this.treeViewDistribut.ExpandAll();
		}

		public static double GetElecEquipElev(Element Equip)
		{
			double num = 0.0;
			FamilyInstance familyInstance = Equip as FamilyInstance;
			if (familyInstance != null)
			{
				Level level = Equip.Document.GetElement(familyInstance.LevelId) as Level;
				if (level != null)
				{
					num = level.Elevation;
					try
					{
						Parameter parameter = familyInstance.get_Parameter(BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM);
						if (parameter != null)
						{
							num += parameter.AsDouble();
						}
					}
					catch
					{
					}
				}
			}
			return num;
		}

		public static XYZ GetElecEquipPositionInfo(ref double dAngle, Element Equip)
		{
			dAngle = 0.0;
			double elecEquipElev = DlgPanelSystemDetect.GetElecEquipElev(Equip);
			XYZ xyz = XYZ.Zero;
			FamilyInstance familyInstance = Equip as FamilyInstance;
			if (familyInstance != null)
			{
				LocationPoint locationPoint = familyInstance.Location as LocationPoint;
				xyz = locationPoint.Point;
				dAngle = locationPoint.Rotation;
			}
			return new XYZ(xyz.X, xyz.Y, elecEquipElev);
		}

		private List<FamilyInstance> GetLevelValidEquips(List<Element> lstEquips, Level level)
		{
			List<FamilyInstance> list = new List<FamilyInstance>();
			foreach (Element element in lstEquips)
			{
				double elecEquipElev = DlgPanelSystemDetect.GetElecEquipElev(element);
				if (this.IsValidElevEquip(elecEquipElev, level))
				{
					list.Add((FamilyInstance)element);
				}
			}
			return list;
		}

		public static void InitElecEquipData(List<Element> lstEquipAll, ref List<Element> lstValidEquips, ref List<Element> lstInValidEquips)
		{
			foreach (Element element in lstEquipAll)
			{
				FamilyInstance familyInstance = element as FamilyInstance;
				bool flag = false;
				foreach (object obj in familyInstance.MEPModel.ConnectorManager.Connectors)
				{
					ConnectorSet allRefs = ((Connector)obj).AllRefs;
					if (allRefs != null)
					{
						IEnumerator enumerator3 = allRefs.GetEnumerator();
						{
							while (enumerator3.MoveNext())
							{
								if (((Connector)enumerator3.Current).Owner.Category.Id.IntegerValue.ToString() == "OST_Wire")
								{
									flag = true;
									break;
								}
							}
						}
						if (flag)
						{
							break;
						}
					}
				}
				if (!flag)
				{
					lstInValidEquips.Add(familyInstance);
				}
				else
				{
					lstValidEquips.Add(familyInstance);
				}
			}
		}

		private void InitElecEquipData()
		{
			this.m_lstElecEquipsInValid.Clear();
			this.m_lstElecEquipsValid.Clear();
			DlgPanelSystemDetect.InitElecEquipData(PanelSystemDetectCommand.GetDocElecEquips(this.doc, this.IDView), ref this.m_lstElecEquipsValid, ref this.m_lstElecEquipsInValid);
			this.m_lstElecEquipsInValidInLinkDoc.Clear();
			this.m_lstElecEquipsValidInLinkDoc.Clear();
			this.m_lstLinkDocs.Clear();
			List<Element> list = new List<Element>();
			IEnumerable<Document> linkDocuments = this.doc.GetLinkDocuments();
			if (linkDocuments != null)
			{
				foreach (Document document in linkDocuments)
				{
					if (document != null)
					{
						this.m_lstLinkDocs.Add(document);
						if (this.CurProj)
						{
							List<Element> docElecEquips = PanelSystemDetectCommand.GetDocElecEquips(document, ElementId.InvalidElementId);
							list.AddRange(docElecEquips);
						}
						else
						{
							List<FamilyInstance> linkDocElemsByViewOutline = DlgPanelSystemDetect.GetLinkDocElemsByViewOutline(document, this.doc.ActiveView);
							list.AddRange(linkDocElemsByViewOutline);
						}
					}
				}
			}
			DlgPanelSystemDetect.InitElecEquipData(list, ref this.m_lstElecEquipsValidInLinkDoc, ref this.m_lstElecEquipsInValidInLinkDoc);
		}

        public static List<FamilyInstance> GetLinkDocElemsByViewOutline(Document doc, Autodesk.Revit.DB.View view)
		{
			Outline outline = null;
			ViewPlan viewPlan = view as ViewPlan;
			if (viewPlan != null)
			{
				PlanViewRange viewRange = viewPlan.GetViewRange();
                ElementId levelId = viewRange.GetLevelId((PlanViewPlane)1);
                ElementId levelId2 = viewRange.GetLevelId((PlanViewPlane)2);
				if (levelId != null && levelId2 != null && levelId.IntegerValue > 0 && levelId2.IntegerValue > 0)
				{
                    double offset = viewRange.GetOffset((PlanViewPlane)1);
					double num = (view.Document.GetElement(levelId) as Level).Elevation + offset;
                    double offset2 = viewRange.GetOffset((PlanViewPlane)2);
					double num2 = (view.Document.GetElement(levelId2) as Level).Elevation + offset2;
					BoundingBoxUV outline2 = viewPlan.Outline;
					double num3 = (double)view.Scale;
					outline = new Outline(new XYZ(outline2.Min.U * num3, outline2.Min.V * num3, num2), new XYZ(outline2.Max.U * num3, outline2.Max.V * num3, num));
				}
			}
			List<FamilyInstance> list = new List<FamilyInstance>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			IEnumerable<FamilyInstance> enumerable;
			if (outline == null)
			{
				enumerable = filteredElementCollector.OfClass(typeof(FamilyInstance)).OfType<FamilyInstance>();
			}
			else
			{
				BoundingBoxIntersectsFilter boundingBoxIntersectsFilter = new BoundingBoxIntersectsFilter(outline);
				enumerable = filteredElementCollector.OfClass(typeof(FamilyInstance)).WherePasses(boundingBoxIntersectsFilter).OfType<FamilyInstance>();
			}
			foreach (FamilyInstance familyInstance in enumerable)
			{
				List<Connector> list2 = new List<Connector>();
				try
				{
					if (familyInstance.MEPModel == null)
					{
						continue;
					}
					if (familyInstance.MEPModel.ConnectorManager == null)
					{
						continue;
					}
					if (familyInstance.MEPModel.ConnectorManager.Connectors == null)
					{
						continue;
					}
					ConnectorSetIterator connectorSetIterator = familyInstance.MEPModel.ConnectorManager.Connectors.ForwardIterator();
					while (connectorSetIterator.MoveNext())
					{
						object obj = connectorSetIterator.Current;
						Connector connector = obj as Connector;
						if (connector.Domain == (Autodesk.Revit.DB.Domain)2)
						{
							list2.Add(connector);
							break;
						}
					}
				}
				catch (Exception)
				{
					continue;
				}
				if (list2.Count != 0)
				{
					list.Add(familyInstance);
				}
			}
			return list;
		}

		private bool IsValidElevEquip(double dEquipElev, Level level)
		{
			int num = -1;
			for (int i = 0; i < this.m_lstSortedLevel.Count; i++)
			{
				if (level.Id == this.m_lstSortedLevel[i].Id)
				{
					num = i;
					break;
				}
			}
			if (num > -1)
			{
				double elevation = level.Elevation;
				double val = double.MaxValue;
				if (num != this.m_lstSortedLevel.Count - 1)
				{
					val = this.m_lstSortedLevel[num + 1].Elevation;
				}
				return Geometry.LessThan(dEquipElev, val) && Geometry.Greaterthan_Or_Equal(dEquipElev, elevation);
			}
			return false;
		}

		public void ShowViewName()
		{
		}

		private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
		{
			this.lvwViewName.Columns[0].Width = this.lvwViewName.Width;
		}

		private void lvwViewName_Click(object sender, EventArgs e)
		{
			if (this.lvwViewName.SelectedIndices.Count > 0)
			{
				this.UpdateEquipListView();
				this.UpdateStatusBar();
			}
		}

		private void DlgPanelSystemDetect_Resize(object sender, EventArgs e)
		{
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			new SubWindow().AssignHandle(this.lvwViewName.Handle);
			new SubWindow().AssignHandle(this.treeViewDistribut.Handle);
			new SubWindow().AssignHandle(this.treeViewNoDistribut.Handle);
		}

		private void DlgPanelSystemDetect_FormClosed(object sender, FormClosedEventArgs e)
		{
			PanelSystemDetectCommand.dlgDetect = null;
			this.m_Hook.HookStop();
		}

		private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.UpdateStatusBar();
		}

		private List<Level> GetSortLevels(Document doc, double bottom, double top)
		{
			List<Level> list = new List<Level>();
			foreach (Element element in new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements())
			{
				Level level = element as Level;
				double elevation = level.Elevation;
				if (Geometry.Greaterthan_Or_Equal(elevation, bottom) && Geometry.Lessthan_Or_Equal(elevation, top))
				{
					list.Add(level);
				}
			}
			list.Sort(new DlgPanelSystemDetect.LevelComparer());
			return list;
		}

		private void treeViewNoDistribut_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			this.OnNodeMouseDoubleClick(e);
		}

		private void treeViewDistribut_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			this.OnNodeMouseDoubleClick(e);
		}

		private void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e)
		{
			if (e.Node.Nodes.Count > 0)
			{
				return;
			}
			FamilyInstance familyInstance = e.Node.Tag as FamilyInstance;
			if (familyInstance == null)
			{
				return;
			}
			if (familyInstance.Document == this.doc)
			{
				Selection selection = this.uiDoc.Selection;
				Common.SetElementVisibility(familyInstance, this.doc);
				RevitVersionFuncs.ClearSelection(selection);
				RevitVersionFuncs.AddToSelection(selection, familyInstance);
				this.uiDoc.ShowElements(familyInstance);
				return;
			}
			DlgPanelSystemDetect.ZoomCenter(familyInstance, this.uiDoc);
		}

		public static void ZoomCenter(Element elem, UIDocument uiDoc)
		{
			try
			{
                Autodesk.Revit.DB.View view = uiDoc.ActiveView;
				IList<UIView> openUIViews = uiDoc.GetOpenUIViews();
				UIView uiview = (from e in openUIViews
				where e.ViewId == view.Id
				select e).FirstOrDefault<UIView>();
				if (openUIViews != null)
				{
					BoundingBoxXYZ boundingBoxXYZ = elem.get_BoundingBox(view);
					XYZ xyz = new XYZ(-2.0, -2.0, 0.0);
					XYZ xyz2 = new XYZ(2.0, 2.0, 0.0);
					uiview.ZoomAndCenterRectangle(boundingBoxXYZ.Min + xyz, boundingBoxXYZ.Max + xyz2);
					RevitVersionFuncs.ClearSelection(uiDoc.Selection);
					List<Element> list = new List<Element>();
					list.Add(elem);
					RevitVersionFuncs.SetSelection(uiDoc.Selection, list);
					uiDoc.RefreshActiveView();
				}
			}
			catch
			{
			}
		}

		private void btnChangeSign_Click(object sender, EventArgs e)
		{
			Dictionary<FamilyInstance, string> familyInstanceInLinkDoc = this.GetFamilyInstanceInLinkDoc(this.treeViewNoDistribut.Nodes[1]);
			if (familyInstanceInLinkDoc.Count == 0)
			{
				MessageBox.Show("没有要处理的构件，请选择");
				return;
			}
			this.GetExchangeSetItemDict();
			if (this.m_dictEleMatchDbFamily.Count == 0)
			{
				foreach (KeyValuePair<FamilyInstance, string> keyValuePair in familyInstanceInLinkDoc)
				{
					FamilyInstance key = keyValuePair.Key;
					string value = keyValuePair.Value;
					EquipmentExchangeSetInfo dbFamilyObj = DlgSignChangeSet.GetDbFamilyObj(key.Symbol, this.m_lstEquipmentExchangeSetItems);
					if (dbFamilyObj == null)
					{
						MessageBox.Show("没有进行相关切换设置，请处理！");
						return;
					}
					this.m_dictEleMatchDbFamily.Add(key, dbFamilyObj);
				}
			}
			Dictionary<FamilyInstance, EquipmentExchangeSetInfo> dictEleMatchDbFamily = this.m_dictEleMatchDbFamily;
			if (dictEleMatchDbFamily.Count == 0)
			{
				MessageBox.Show("没有进行切换设置，请处理");
				return;
			}
			DlgPanelSystemDetect dlgPanelSystemDetect = this;
			this.m_cmdExtrenal.SetDetectDlg(ref dlgPanelSystemDetect);
			bool @checked = this.checkBoxRotate.Checked;
			this.m_cmdExtrenal.SetExchangeSetInfo(dictEleMatchDbFamily, @checked);
			this.m_cmdExtrenal.Request.Make(RequestId.Exchange);
			this.m_exEvent.Raise();
		}

		private void btnChangeSet_Click(object sender, EventArgs e)
		{
			Dictionary<FamilyInstance, string> familyInstanceInLinkDoc = this.GetFamilyInstanceInLinkDoc(this.treeViewNoDistribut.Nodes[1]);
			if (familyInstanceInLinkDoc.Count == 0)
			{
				MessageBox.Show("没有要处理的构件，请选择");
				return;
			}
			this.GetExchangeSetItemDict();
			this.m_dictEleMatchDbFamily.Clear();
			DlgSignChangeSet dlgSignChangeSet = new DlgSignChangeSet(familyInstanceInLinkDoc, this.cmdData, ref this.m_lstEquipmentExchangeSetItems);
			if (DialogResult.OK != dlgSignChangeSet.ShowDialog())
			{
				return;
			}
			this.m_dictEleMatchDbFamily = dlgSignChangeSet.GetUserSetMatch();
			this.SaveSelectInfo(null);
		}

		private void GetExchangeSetItemDict()
		{
			foreach (ExchangeSetItem exchangeSetItem in this.m_EquipExchangeXMLSetting.m_lstExchangeSet)
			{
				bool flag = false;
				EquipmentExchangeSetInfo equipmentExchangeSetInfo = null;
				foreach (EquipmentExchangeSetInfo equipmentExchangeSetInfo2 in this.m_lstEquipmentExchangeSetItems)
				{
					if (equipmentExchangeSetInfo2.OldEquipName == exchangeSetItem.m_strOrigonEquipName && equipmentExchangeSetInfo2.OldEquipType == exchangeSetItem.m_strOrigonEquipType)
					{
						flag = true;
						equipmentExchangeSetInfo = equipmentExchangeSetInfo2;
						break;
					}
				}
				if (!flag)
				{
					equipmentExchangeSetInfo = new EquipmentExchangeSetInfo();
					this.m_lstEquipmentExchangeSetItems.Add(equipmentExchangeSetInfo);
				}
				equipmentExchangeSetInfo.EquipmentTypeName = exchangeSetItem.m_strExchangeEquipType;
				equipmentExchangeSetInfo.OldEquipType = exchangeSetItem.m_strOrigonEquipType;
				equipmentExchangeSetInfo.OldEquipName = exchangeSetItem.m_strOrigonEquipName;
				equipmentExchangeSetInfo.m_selDbFamilyObject = new DbFamilyObject();
				equipmentExchangeSetInfo.m_selDbFamilyObject.Name = exchangeSetItem.m_strExchangeEquipName;
				equipmentExchangeSetInfo.m_selDbFamilyObject.Family = exchangeSetItem.m_strExchangeEquipFilePath;
				equipmentExchangeSetInfo.EquipmentType = (EquipmentType)Enum.ToObject(typeof(EquipmentType), exchangeSetItem.m_nEquipType);
			}
		}

		private Dictionary<FamilyInstance, string> GetFamilyInstanceInLinkDoc(TreeNode treeNode)
		{
			Dictionary<FamilyInstance, string> dictionary = new Dictionary<FamilyInstance, string>();
			if (treeNode.Nodes.Count != 0)
			{
				foreach (object obj in treeNode.Nodes)
				{
					TreeNode treeNode2 = (TreeNode)obj;
					foreach (KeyValuePair<FamilyInstance, string> keyValuePair in this.GetFamilyInstanceInLinkDoc(treeNode2))
					{
						dictionary.Add(keyValuePair.Key, keyValuePair.Value);
					}
				}
				return dictionary;
			}
			FamilyInstance familyInstance = treeNode.Tag as FamilyInstance;
			if (familyInstance == null || !treeNode.Checked)
			{
				return dictionary;
			}
			string value = treeNode.Parent.Parent.Parent.Tag as string;
			dictionary.Add(familyInstance, value);
			return dictionary;
		}

		private Dictionary<FamilyInstance, TreeNode> GetFamilyInstanceNodeInLinkDoc(TreeNode treeNode)
		{
			Dictionary<FamilyInstance, TreeNode> dictionary = new Dictionary<FamilyInstance, TreeNode>();
			if (treeNode.Nodes.Count != 0)
			{
				foreach (object obj in treeNode.Nodes)
				{
					TreeNode treeNode2 = (TreeNode)obj;
					foreach (KeyValuePair<FamilyInstance, TreeNode> keyValuePair in this.GetFamilyInstanceNodeInLinkDoc(treeNode2))
					{
						dictionary.Add(keyValuePair.Key, keyValuePair.Value);
					}
				}
				return dictionary;
			}
			FamilyInstance familyInstance = treeNode.Tag as FamilyInstance;
			if (familyInstance == null)
			{
				return dictionary;
			}
			dictionary.Add(familyInstance, treeNode);
			return dictionary;
		}

		private string GetCurLevelName()
		{
			Level level;
			if (this.CurProj)
			{
				ElementId elementId = this.lvwViewName.SelectedItems[0].Tag as ElementId;
				level = (this.doc.GetElement(elementId) as Level);
			}
			else
			{
				ElementId elementId2 = this.lvwViewName.SelectedItems[0].Tag as ElementId;
				level = (this.doc.GetElement(elementId2) as Level);
			}
			if (level == null)
			{
				return "";
			}
			return level.Name;
		}

		private void InitSelInfo(TreeNode nodeTree)
		{
			if (this.m_EquipExchangeXMLSetting.m_lstLinkEleSet.Count == 0)
			{
				return;
			}
			string curLevelName = this.GetCurLevelName();
			foreach (KeyValuePair<FamilyInstance, TreeNode> keyValuePair in this.GetFamilyInstanceNodeInLinkDoc(nodeTree))
			{
				FamilyInstance key = keyValuePair.Key;
				TreeNode value = keyValuePair.Value;
				bool bChecked = false;
				foreach (LinkEleItem linkEleItem in this.m_EquipExchangeXMLSetting.m_lstLinkEleSet)
				{
					if (linkEleItem.m_lID == key.Id.IntegerValue && linkEleItem.m_strLinkDoc == key.Document.PathName && curLevelName == linkEleItem.m_strViewLevel)
					{
						bChecked = true;
						break;
					}
				}
				this.treeViewNoDistribut.SetCheckStatus(value, bChecked);
			}
		}

		public void SaveSelectInfo(Dictionary<FamilyInstance, ElementId> dictExchangePairs)
		{
			Dictionary<FamilyInstance, string> familyInstanceInLinkDoc = this.GetFamilyInstanceInLinkDoc(this.treeViewNoDistribut.Nodes[1]);
			string pathName = this.doc.PathName;
			if (pathName != this.m_EquipExchangeXMLSetting.m_strPrjName)
			{
				this.m_EquipExchangeXMLSetting.Clear();
			}
			if (familyInstanceInLinkDoc.Count == 0)
			{
				return;
			}
			this.m_EquipExchangeXMLSetting.m_strPrjName = pathName;
			string curLevelName = this.GetCurLevelName();
			foreach (KeyValuePair<FamilyInstance, string> keyValuePair in familyInstanceInLinkDoc)
			{
				FamilyInstance key = keyValuePair.Key;
				string value = keyValuePair.Value;
				bool flag = false;
				LinkEleItem linkEleItem = null;
				foreach (LinkEleItem linkEleItem2 in this.m_EquipExchangeXMLSetting.m_lstLinkEleSet)
				{
					if (linkEleItem2.m_lID == key.Id.IntegerValue && linkEleItem2.m_strLinkDoc == key.Document.PathName && curLevelName == linkEleItem2.m_strViewLevel)
					{
						linkEleItem = linkEleItem2;
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					linkEleItem = new LinkEleItem();
					this.m_EquipExchangeXMLSetting.m_lstLinkEleSet.Add(linkEleItem);
				}
				linkEleItem.m_lID = key.Id.IntegerValue;
				linkEleItem.m_strLinkDoc = key.Document.PathName;
				linkEleItem.m_strViewLevel = curLevelName;
				if (dictExchangePairs != null)
				{
					foreach (KeyValuePair<FamilyInstance, ElementId> keyValuePair2 in dictExchangePairs)
					{
						if (linkEleItem.m_lID == keyValuePair2.Key.Id.IntegerValue)
						{
							linkEleItem.m_lIDCurExchange = keyValuePair2.Value.IntegerValue;
							break;
						}
					}
				}
			}
			foreach (EquipmentExchangeSetInfo equipmentExchangeSetInfo in this.m_lstEquipmentExchangeSetItems)
			{
				bool flag2 = false;
				ExchangeSetItem exchangeSetItem = null;
				foreach (ExchangeSetItem exchangeSetItem2 in this.m_EquipExchangeXMLSetting.m_lstExchangeSet)
				{
					if (equipmentExchangeSetInfo.OldEquipName == exchangeSetItem2.m_strOrigonEquipName && equipmentExchangeSetInfo.OldEquipType == exchangeSetItem2.m_strOrigonEquipType)
					{
						flag2 = true;
						exchangeSetItem = exchangeSetItem2;
						break;
					}
				}
				if (!flag2)
				{
					exchangeSetItem = new ExchangeSetItem();
					this.m_EquipExchangeXMLSetting.m_lstExchangeSet.Add(exchangeSetItem);
				}
				exchangeSetItem.m_strOrigonEquipType = equipmentExchangeSetInfo.OldEquipType;
				exchangeSetItem.m_strOrigonEquipName = equipmentExchangeSetInfo.OldEquipName;
				exchangeSetItem.m_strExchangeEquipType = equipmentExchangeSetInfo.EquipmentTypeName;
				exchangeSetItem.m_strExchangeEquipName = Path.GetFileNameWithoutExtension(equipmentExchangeSetInfo.DbFamilyObjectCur.Family);
				exchangeSetItem.m_strExchangeEquipFilePath = equipmentExchangeSetInfo.DbFamilyObjectCur.Family;
				if (exchangeSetItem.m_strExchangeEquipName == "" && equipmentExchangeSetInfo.FamilySymbolCur != null)
				{
					exchangeSetItem.m_strExchangeEquipName = equipmentExchangeSetInfo.FamilySymbolCur.FamilyName;
				}
			}
			this.m_EquipExchangeXMLSetting.Save();
		}

		private void btnKeywordSet_Click(object sender, EventArgs e)
		{
			Dictionary<FamilyInstance, string> familyInstanceInLinkDoc = this.GetFamilyInstanceInLinkDoc(this.treeViewNoDistribut.Nodes[1]);
			DlgEquipmentKeyWordSet dlgEquipmentKeyWordSet = new DlgEquipmentKeyWordSet(this.cmdData, familyInstanceInLinkDoc);
			dlgEquipmentKeyWordSet.ShowDialog();
			this.UpdateEquipmentExchangeItems(dlgEquipmentKeyWordSet.m_xmlDoc);
		}

		private void UpdateEquipmentExchangeItems(XmlDocument xmlDoc)
		{
			List<KeyWordSet> lstKeywordSet = this.GetkeywordSetInfo(xmlDoc);
			this.UpdateEquipmentExchangeSetItems(lstKeywordSet);
			this.UpdateEquipExchangeXMLSetting();
		}

		private List<KeyWordSet> GetkeywordSetInfo(XmlDocument xmlDoc)
		{
			List<KeyWordSet> list = new List<KeyWordSet>();
			if (xmlDoc != null)
			{
				XmlNodeList xmlNodeList = xmlDoc.SelectSingleNode("KewWordSet").SelectNodes("KewWord");
				if (xmlNodeList != null)
				{
					foreach (object obj in xmlNodeList)
					{
						XmlElement xmlElement = ((XmlNode)obj) as XmlElement;
						KeyWordSet keyWordSet = new KeyWordSet();
						keyWordSet.KewWord = xmlElement.GetAttribute("Name");
						XmlNode xmlNode = xmlElement.SelectSingleNode("Item");
						keyWordSet.OrigonEquipType = (xmlNode as XmlElement).GetAttribute("OrigonEquipType");
						keyWordSet.EquipName = (xmlNode as XmlElement).GetAttribute("EquipName");
						keyWordSet.ClassName = (xmlNode as XmlElement).GetAttribute("Category");
						keyWordSet.FamilyPath = (xmlNode as XmlElement).GetAttribute("FamilyPath");
						keyWordSet.EquipType = (xmlNode as XmlElement).GetAttribute("EquipType");
						list.Add(keyWordSet);
					}
				}
			}
			return list;
		}

		private void UpdateEquipmentExchangeSetItems(List<KeyWordSet> lstKeywordSet)
		{
			if (0 < lstKeywordSet.Count)
			{
				foreach (KeyWordSet keyWordSet in lstKeywordSet)
				{
					bool flag = false;
					EquipmentExchangeSetInfo equipmentExchangeSetInfo = new EquipmentExchangeSetInfo();
					equipmentExchangeSetInfo.OldEquipType = keyWordSet.OrigonEquipType;
					equipmentExchangeSetInfo.OldEquipName = keyWordSet.KewWord;
					equipmentExchangeSetInfo.EquipmentTypeName = keyWordSet.ClassName;
					equipmentExchangeSetInfo.m_selDbFamilyObject = new DbFamilyObject();
					equipmentExchangeSetInfo.m_selDbFamilyObject.Name = keyWordSet.EquipName;
					equipmentExchangeSetInfo.m_selDbFamilyObject.Family = keyWordSet.FamilyPath;
					if ("" != keyWordSet.EquipType)
					{
						equipmentExchangeSetInfo.EquipmentType = (EquipmentType)Enum.ToObject(typeof(EquipmentType), Convert.ToInt32(keyWordSet.EquipType));
					}
					for (int i = 0; i < this.m_lstEquipmentExchangeSetItems.Count; i++)
					{
						if (this.m_lstEquipmentExchangeSetItems.ElementAt(i).OldEquipName == keyWordSet.KewWord)
						{
							flag = true;
							this.m_lstEquipmentExchangeSetItems.RemoveAt(i);
							this.m_lstEquipmentExchangeSetItems.Insert(i, equipmentExchangeSetInfo);
							break;
						}
					}
					if (!flag)
					{
						this.m_lstEquipmentExchangeSetItems.Add(equipmentExchangeSetInfo);
					}
				}
			}
		}

		private void UpdateEquipExchangeXMLSetting()
		{
			foreach (EquipmentExchangeSetInfo equipmentExchangeSetInfo in this.m_lstEquipmentExchangeSetItems)
			{
				ExchangeSetItem exchangeSetItem = new ExchangeSetItem();
				exchangeSetItem.m_strOrigonEquipType = equipmentExchangeSetInfo.OldEquipType;
				exchangeSetItem.m_strOrigonEquipName = equipmentExchangeSetInfo.OldEquipName;
				exchangeSetItem.m_strExchangeEquipType = equipmentExchangeSetInfo.EquipmentTypeName;
				exchangeSetItem.m_strExchangeEquipName = Path.GetFileNameWithoutExtension(equipmentExchangeSetInfo.DbFamilyObjectCur.Family);
				exchangeSetItem.m_strExchangeEquipFilePath = equipmentExchangeSetInfo.DbFamilyObjectCur.Family;
				if (exchangeSetItem.m_strExchangeEquipName == "" && equipmentExchangeSetInfo.FamilySymbolCur != null)
				{
					exchangeSetItem.m_strExchangeEquipName = equipmentExchangeSetInfo.FamilySymbolCur.FamilyName;
				}
				bool flag = false;
				for (int i = 0; i < this.m_EquipExchangeXMLSetting.m_lstExchangeSet.Count; i++)
				{
					if (this.m_EquipExchangeXMLSetting.m_lstExchangeSet.ElementAt(i).m_strOrigonEquipName == equipmentExchangeSetInfo.OldEquipName)
					{
						flag = true;
						this.m_EquipExchangeXMLSetting.m_lstExchangeSet.RemoveAt(i);
						this.m_EquipExchangeXMLSetting.m_lstExchangeSet.Insert(i, exchangeSetItem);
						break;
					}
				}
				if (!flag)
				{
					this.m_EquipExchangeXMLSetting.m_lstExchangeSet.Add(exchangeSetItem);
				}
			}
			this.m_EquipExchangeXMLSetting.Save();
		}

		private ExternalCommandData cmdData;

		private Document doc;

		private UIDocument uiDoc;

		private KeyboardHook m_Hook;

		private bool m_bProj = true;

		private List<Level> m_lstSortedLevel;

		private List<Element> m_lstElecEquipsValid = new List<Element>();

		private List<Element> m_lstElecEquipsInValid = new List<Element>();

		private List<Element> m_lstElecEquipsValidInLinkDoc = new List<Element>();

		private List<Element> m_lstElecEquipsInValidInLinkDoc = new List<Element>();

		private List<Document> m_lstLinkDocs = new List<Document>();

		private EquipExchangeExternalHandler m_cmdExtrenal;

		private ExternalEvent m_exEvent;

		private List<EquipmentExchangeSetInfo> m_lstEquipmentExchangeSetItems = new List<EquipmentExchangeSetInfo>();

		private Dictionary<FamilyInstance, EquipmentExchangeSetInfo> m_dictEleMatchDbFamily;

		private EquipExchangeXMLSetting m_EquipExchangeXMLSetting;

		private class LevelComparer : IComparer<Level>
		{
			public int Compare(Level x, Level y)
			{
				return x.Elevation.CompareTo(y.Elevation);
			}
		}
	}
}
